package com.huluobo.a2204parkdemo.signIn

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2204parkdemo.R
import com.huluobo.a2204parkdemo.databinding.ActivitySignInBinding
import com.huluobo.base.mvvm.BaseActivity
import com.huluobo.base.net.Const
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.text.SimpleDateFormat

@AndroidEntryPoint
class SignInActivity : BaseActivity<ActivitySignInBinding, SignInViewModel>() {
    override fun initData() {
        viewModel.signInSuccess.observe(this) {
            SPUtils.getInstance().put(Const.PARAM_IS_SIGN, true)
            ToastUtils.showLong("签到成功")
            binding.signInBtn.text = "签退"
        }

        viewModel.signOutSuccess.observe(this) {
            SPUtils.getInstance().put(Const.PARAM_IS_SIGN, false)
            ToastUtils.showLong("签退成功")
            binding.signInBtn.text = "签到"
        }
    }

    override fun initView() {
        binding.signInHeader.headerBack.setOnClickListener { finish() }
        binding.signInHeader.headerTitle.text = "签到/签退"

        if (SPUtils.getInstance().getBoolean(Const.PARAM_IS_SIGN)) {
            binding.signInBtn.text = "签退"
        } else {
            binding.signInBtn.text = "签到"
        }

        binding.signInBtn.setOnClickListener {
            val address = "天津市"
            val time = getTime()
            val map = mutableMapOf<String, Any>()
            if (SPUtils.getInstance().getBoolean(Const.PARAM_IS_SIGN)) {
                map[Const.PARAM_END_ADDRESS] = address
                map[Const.PARAM_END_TIME] = time
                map[Const.PARAM_START_ADDRESS] = address
                map[Const.PARAM_START_TIME] = time
                map[Const.PARAM_USER_ID] = SPUtils.getInstance().getInt(Const.PARAM_UID)
                val json = Gson().toJson(map)
                val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                viewModel.signOut(body)
            } else {
                map[Const.PARAM_START_ADDRESS] = address
                map[Const.PARAM_START_TIME] = time
                map[Const.PARAM_END_ADDRESS] = address
                map[Const.PARAM_END_TIME] = time
                map[Const.PARAM_USER_ID] = SPUtils.getInstance().getInt(Const.PARAM_UID)

                val json = Gson().toJson(map)
                val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                viewModel.signIn(body)
            }
        }
    }
}